from typing import Any, Dict, List, Optional, TypeVar, Generic
from pydantic import BaseModel, Field
from datetime import datetime

T = TypeVar('T')

class BaseResponse(BaseModel):
    """基础响应格式"""
    success: bool = True
    message: str = ""
    timestamp: str = Field(default_factory=lambda: datetime.utcnow().isoformat())

class DataResponse(BaseResponse, Generic[T]):
    """包含数据的响应格式"""
    data: T

class ListResponse(BaseResponse, Generic[T]):
    """列表响应格式"""
    data: List[T]
    total_count: int
    pagination: Optional[Dict[str, Any]] = None
    summary: Optional[Dict[str, Any]] = None

class ErrorResponse(BaseResponse):
    """错误响应格式"""
    success: bool = False
    error_code: Optional[str] = None
    error_type: Optional[str] = None
    details: Optional[Dict[str, Any]] = None

# 简单的工具函数，避免复杂的类继承
def success_response(data: Any = None, message: str = "操作成功") -> Dict[str, Any]:
    """创建成功响应"""
    response = {
        "success": True,
        "message": message,
        "timestamp": datetime.utcnow().isoformat()
    }
    if data is not None:
        response["data"] = data
    return response

def list_response(
    items: List[Any], 
    total_count: int, 
    message: str = "查询成功",
    pagination: Optional[Dict[str, Any]] = None,
    summary: Optional[Dict[str, Any]] = None
) -> Dict[str, Any]:
    """创建列表响应"""
    response = {
        "success": True,
        "message": message,
        "timestamp": datetime.utcnow().isoformat(),
        "data": items,
        "total_count": total_count,
        "pagination": pagination
    }
    if summary is not None:
        response["summary"] = summary
    return response

def error_response(
    message: str,
    error_code: Optional[str] = None,
    error_type: Optional[str] = None,
    details: Optional[Dict[str, Any]] = None
) -> Dict[str, Any]:
    """创建错误响应"""
    return {
        "success": False,
        "message": message,
        "timestamp": datetime.utcnow().isoformat(),
        "error_code": error_code,
        "error_type": error_type,
        "details": details
    }

def create_pagination_info(
    current_page: int,
    page_size: int,
    total_count: int
) -> Dict[str, Any]:
    """创建分页信息"""
    total_pages = (total_count + page_size - 1) // page_size
    return {
        "current_page": current_page,
        "page_size": page_size,
        "total_pages": total_pages,
        "total_count": total_count,
        "has_next": current_page < total_pages,
        "has_prev": current_page > 1
    } 